/**
 * COPYRIGHT. Harry Wu 2011. ALL RIGHTS RESERVED.
 * Project: just-ice
 * Author: Harry Wu <harrywu304@gmail.com>
 * Created On: Jul 1, 2011 2:57:59 PM
 *
*/ 
package org.justframework.ext.ice;

import org.justframework.core.ServerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import Ice.Communicator;
import Ice.InitializationData;
import Ice.ObjectAdapter;
import Ice.Properties;
import Ice.ServantLocator;
import Ice.Util;

/**
 * ice server connector
 *
 */
public class IceServer implements ServerConnector {
	
	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(IceServer.class);
	
	private int port;
	
	/**
	 * Ice.Communicator
	 */
	private Communicator ic = null;

	/**
	 * rpc代理适配器
	 */
	private ObjectAdapter adapter = null;

	/**
	 * 服务定位器
	 */
	private ServantLocator servantLocator = null;

	/* (non-Javadoc)
	 * @see org.justframework.core.ServerConnector#getPort()
	 */
	public int getPort() {
		return port;
	}

	/* (non-Javadoc)
	 * @see org.justframework.core.ServerConnector#setPort(int)
	 */
	public void setPort(int port) {
		this.port = port;
	}

	/* (non-Javadoc)
	 * @see org.justframework.core.ServerConnector#startup()
	 */
	public void startup() {
		int status = 0;
		try {
			Properties prop = Util.createProperties();
			prop.setProperty("Ice.MessageSizeMax", "1024");
			prop.setProperty("Ice.ThreadPool.Server.Size", "10");
			prop.setProperty("Ice.ThreadPool.Server.SizeMax", "500");
			prop.setProperty("Ice.ThreadPool.Server.SizeWarn", "480");
			prop.setProperty("Ice.TCP.RcvSize", "65535");
			prop.setProperty("Ice.TCP.SndSize", "65535");
			
			// initial Ice.Communicator
			InitializationData initData = new InitializationData();
			initData.properties = prop;
			ic = Ice.Util.initialize(initData);
			// initial ICE adapter
			Ice.ObjectAdapter adapter = ic.createObjectAdapterWithEndpoints(
					"ZerocRpcAdapter", "tcp -p " + port);

			// mode one：add ICE handler
			Ice.Object object = new IceHandlerAdapter();
			adapter.add(object, Ice.Util.stringToIdentity("ZerocRpc"));

			// mode two：add custom servant locator
			// adapter.addServantLocator(new AppServantLocator(), "");

			// 启动ICE服务
			adapter.activate();
			ic.waitForShutdown();
		} catch (Exception e) {
			e.printStackTrace();
			status = 1;
		} finally {
			if (ic != null) {
				ic.destroy();
			}
		}
		System.exit(status);
	}

	/* (non-Javadoc)
	 * @see org.justframework.core.ServerConnector#shutdown()
	 */
	public void shutdown() {
		adapter.deactivate();
		adapter.destroy();
		ic.destroy();
	}

}
